﻿using DLL;
using NursingFormSystem.Common;
using NursingFormSystem.Model;
using System;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace NursingFormSystem.SBAR
{
    public partial class AddSBAR : Form
    {
        #region 变量声明
        public NursingFormSystem.NurFormsService.NursingForm formService = new NursingFormSystem.NurFormsService.NursingForm();
        NursingFormSystem.WebReference2.FunctionAndPermissions WebService = new NursingFormSystem.WebReference2.FunctionAndPermissions();
        NursingFormRecord record = new NursingFormRecord();
        NursingPublicRelation relation = new NursingPublicRelation();
        Tb_User LoginUser;   //员工信息
        string Id = string.Empty;
        PatientInfo Patientinfo;    //患者信息
        DataTable patients = null;
        #endregion

        #region 窗体函数
        public AddSBAR(Tb_User loginUser, PatientInfo patientInfo, string id)
        {
            InitializeComponent();
            //成员变量
            this.LoginUser = loginUser;
            this.Patientinfo = patientInfo;
            this.Id = id;
            //绑定数据
            BindInfo(Id);
            InitData();
        }
        public AddSBAR(string[] loginUser, string[] patientInfo)
        {
            InitializeComponent();
            //成员变量
            this.LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            this.Patientinfo = ArrayToObject.ArrayToPatientInfo(patientInfo);
            this.Id = string.Empty;
            //绑定数据
            BindInfo(this.Id);
            InitData();
        }
        public AddSBAR(string[] loginUser, string[] patientInfo, string id)
        {
            InitializeComponent();
            //成员变量
            this.LoginUser = ArrayToObject.ArrayToLoginUser(loginUser);
            this.Patientinfo = ArrayToObject.ArrayToPatientInfo(patientInfo);
            this.Id = id;
            //绑定数据
            BindInfo(this.Id);
            InitData();
        }
        #endregion

        #region  初始化患者信息
        /// <summary>
        /// 初始化相关在院 患者信息下拉框按钮；
        /// </summary>
        private void InitData()
        {
            comboBox_patientss.Properties.DropDownRows = 15;//设置初始化的下拉值
            comboBox_patientss.Properties.DropDownItemHeight = 20;//下拉框的高度
            comboBox_patientss.Properties.Items.Clear();
            patients = WebService.getDepartmentCodePatients(LoginUser.DepartmentCode).D;
            if (patients != null)
            {
                foreach (DataRow row in patients.Rows)
                {
                    comboBox_patientss.Properties.Items.Add(row["PATIENT_NAME"] + "  " + row["BED_NO"] + "床");
                    if (string.IsNullOrEmpty(Id))
                    {
                        comboBox_patientss.SelectedIndex = 0;
                    }
                    else
                    {
                        string sql = string.Format("SELECT top 1 * FROM NursingFormRecord(NOLOCK) WHERE id='{0}'", Id);
                        DataSet dataset = SqlHelper.ExecuteDataset(sql, System.Data.CommandType.Text);
                        DataRow row1 = dataset.Tables[0].Rows[0];
                        comboBox_patientss.Text = row1["PatientName"] + "  " + row1["BedNo"] + "床";
                    }
                }
            }
            GetCurPatientInfo();
            txtBingrenzongshu.Text = patients.Rows.Count.ToString(); //患者总数
            txtYijibingren.Text = patients.Select("NURSING='Ⅰ级护理'").Count().ToString();       //一级患者人数
        }
        #endregion

        #region 患者信息下拉改变事件
        private void comboBox_patients_SelectedIndexChanged(object sender, EventArgs e)
        {
            string str = comboBox_patientss.SelectedText.ToString();//获取选中的项
            GetCurPatientInfo();
        }
        #endregion

        #region 获取当前选中患者的信息
        private void GetCurPatientInfo()
        {
            DataRow row = patients.NewRow();
            if (comboBox_patientss.SelectedIndex < 0) return;
            row = patients.Rows[comboBox_patientss.SelectedIndex];
            textXingMing.Text = row["PATIENT_NAME"].ToString();//姓名
            textXingBie.Text = row["SEX"].ToString();//性别
            txtBingAnHao.Text = row["PATIENT_ID"].ToString();//病案号
            textChuangHao.Text = row["BED_NO"].ToString();//床号
            memoRuYuanZhenDuan.Text = row["DIAGNOSE"].ToString();//诊断信息
        }
        #endregion

        #region 时间双击事件
        private void txtShijian_DoubleClick(object sender, EventArgs e)
        {
            txtShiJian.Text = DateTime.Now.ToString("HH:mm");
        }
        #endregion

        #region 设置 enter键当做Tab切换
        /// <summary>
        /// 设置 enter键当做Tab切换
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>

        private void TemperatureEdit1_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyData == Keys.Enter)
            {
                SendKeys.SendWait("{Tab}");
            }
        }
        #endregion

        #region 取消
        private void simplequxiao_Click(object sender, EventArgs e)
        {
            this.DialogResult = DialogResult.OK;
        }
        #endregion

        #region 保存
        private void simplebaocun_Click(object sender, EventArgs e)
        {
            //日期判断
            if (string.IsNullOrEmpty(txtRiQi.Text.Trim()))
                txtRiQi.DateTime = DateTime.Now;
            //时间判断
            if (!txtShiJian.Text.Contains(":"))
            {
                txtShiJian.Focus();
                MessageBox.Show("时间需HH:mm格式，或使用双击显示当前时间");
                return;
            }
            SBARHandOverDuty sbar = new SBARHandOverDuty();
            sbar.RiQi = txtRiQi.DateTime.ToString("yyyy-MM-dd");   //日期
            sbar.ShiJian = DateTimeTran.TimeFillZero(txtShiJian.Text);   //时间
            sbar.BingRenLieBie = (cheBingrenLeibie1.Checked ? 1 : 0) + "#" + (cheBingrenLeibie2.Checked ? 1 : 0) + "#" + (cheBingrenLeibie3.Checked ? 1 : 0) + "#" + (cheBingrenLeibie4.Checked ? 1 : 0);//病人类别
            sbar.HuLiJiBie = (cheHuliJibie1.Checked ? 1 : 0) + "#" + (cheHuliJibie2.Checked ? 1 : 0) + "#" + (cheHuliJibie3.Checked ? 1 : 0);  //护理级别
            sbar.RuYuanZhenDuan = memoRuYuanZhenDuan.Text;  //入院诊断
            sbar.JiaoBanBingQingXianZhuang = memoXianZhuang.Text; //现状
            sbar.JiaoBanBingQingBeiJing = memoBeiJing.Text; //背景
            sbar.JiaoBanBingQingPingGu = memoPingGu.Text;  //评估
            sbar.JiaoBanBingQingJianYi = memoJianYi.Text;  //建议
            if (string.IsNullOrEmpty(Id))
                sbar.JiaoBanRen = LoginUser.UserName;
            else
                sbar.JiaoBanRen = txtJiaoBanRen.Text;    //交班人签名
            //文书关联表主要存储 病人总数.新入院.出院等字段
            SBARNursingRelation rela = new SBARNursingRelation();
            rela.BingRenZongshu = txtBingrenzongshu.Text;  //病人总数
            rela.XinRuYuan = txtXinruyuan.Text; //新入院
            rela.ChuYuan = txtChuyuan.Text; //出院
            rela.ZhuanRu = txtZhuanru.Text; //转入
            rela.ZhuanChu = txtZhuanchu.Text; //转出
            rela.SiWang = txtSiwang.Text; //死亡
            rela.YiJiBingRen = txtYijibingren.Text;  //一级病人
            DataRow row = patients.NewRow();
            row = patients.Rows[comboBox_patientss.SelectedIndex];
            record.FormId = (int)FormType.HandOverDuty;  //表单ID
            record.FormName = EnumHelper.GetDescription(FormType.HandOverDuty);    //表单名字
            record.PatientId = txtBingAnHao.Text;      //住院号
            record.VisitId = Convert.ToInt32(row["VISIT_ID"].ToString());   //住院次数
            record.PatientName = textXingMing.Text;    //患者姓名
            record.BedNo = textChuangHao.Text;   //床号
            record.DepartmentId = row["DEPARTMENT_ID"].ToString(); //Patientinfo.DEPARTMENT_ID;   //当前科室ID
            record.DepartmentName = row["DEPARTMENT_NAME"].ToString(); // Patientinfo.DEPARTMENT_NAME;   //当前科室名字
            record.AreaId = row["NURSE_CELL_CODE"].ToString(); //Patientinfo.NURSE_CELL_CODE;    //当前患者病区ID
            record.AreaName = row["NURSE_CELL_NAME"].ToString(); //Patientinfo.NURSE_CELL_NAME;    //当前患者病区名称
            record.AssessmentDate = Convert.ToDateTime(sbar.RiQi + " " + sbar.ShiJian);//日期
            record.Id = Id == "" ? 0 : Convert.ToInt32(Id);
            record.NursingFormData = XmlUtil.ObjectToXML(sbar, Encoding.UTF8);
            //通用文书关系
            relation.FormId = (int)FormType.HandOverDuty;  //表单ID
            relation.FormName = EnumHelper.GetDescription(FormType.HandOverDuty);    //表单名字
            relation.AreaId = row["NURSE_CELL_CODE"].ToString();    //当前患者病区ID
            relation.AreaName = row["NURSE_CELL_NAME"].ToString();  //当前患者病区名称
            relation.AssessmentDate = Convert.ToDateTime(sbar.RiQi);//日期
            relation.NursingFormData = XmlUtil.ObjectToXML(rela, Encoding.UTF8);
            relation.Id = Id == "" ? 0 : Convert.ToInt32(Id);
            var ret = formService.SetNursingFormRecord(Newtonsoft.Json.JsonConvert.SerializeObject(record));
            string sql = @"if(EXISTS (SELECT TOP 1 Id FROM NursingPublicRelation(NOLOCK) WHERE FormId = '{0}' AND AreaId = '{2}' AND AssessmentDate = '{5}'))
                            BEGIN UPDATE NursingPublicRelation SET NursingFormData='{4}'  WHERE FormId = '{0}' AND AreaId = '{2}' AND AssessmentDate = '{5}' END ELSE BEGIN
                           INSERT INTO [NursingPublicRelation] ([FormId],[FormName],[AreaId] ,[AreaName] ,[NursingFormData] ,[AssessmentDate] ,[CreateTime])
                            VALUES('{0}','{1}','{2}' ,'{3}','{4}','{5}','{6}') END";
            sql = string.Format(sql, relation.FormId, relation.FormName, relation.AreaId, relation.AreaName, relation.NursingFormData, relation.AssessmentDate, DateTime.Now);
            int count = SqlHelper.ExecuteNonQuery(sql);
            if (ret.Code == 1 && count > 0)
            {
                MessageBox.Show(ret.M);
                this.DialogResult = DialogResult.OK;
            }
            else
            {
                MessageBox.Show(ret.M);
            }
        }
        #endregion

        #region 显示赋值
        public void BindInfo(string Id)
        {
            txtJiaoBanRen.Text = LoginUser.UserName;   //交班人签名
            txtRiQi.DateTime = DateTime.Now;    //默认显示当前日期
            txtShiJian.Text = DateTime.Now.ToString("HH:mm");
            //关联人数数据赋值
            string sqlStr = string.Format("SELECT NursingFormData FROM NursingPublicRelation(NOLOCK) WHERE FormId='{0}'and AreaId='{1}' and AssessmentDate='{2}' ",
              (int)FormType.HandOverDuty, Patientinfo.NURSE_CELL_CODE, this.txtRiQi.Text);
            DataTable table = SqlHelper.ExecuteDataset(sqlStr, System.Data.CommandType.Text).Tables[0];
            if (table != null && table.Rows.Count > 0)
            {
                var SNursingFormData1 = Convert.ToString(table.Rows[0]["NursingFormData"]);
                SBARNursingRelation nr = new SBARNursingRelation();
                nr = XmlUtil.XMLToObject<SBARNursingRelation>(SNursingFormData1, Encoding.UTF8);
                txtBingrenzongshu.Text = nr.BingRenZongshu;  //病人总数
                txtXinruyuan.Text = nr.XinRuYuan;  //新入院
                txtChuyuan.Text = nr.ChuYuan;  //出院人数
                txtZhuanru.Text = nr.ZhuanRu; //转入人数
                txtZhuanchu.Text = nr.ZhuanChu;  //转出人数
                txtSiwang.Text = nr.SiWang;  //死亡人数
                txtYijibingren.Text = nr.YiJiBingRen;  //一级病人数
            }
            if (string.IsNullOrEmpty(Id)) return;
            string sql = string.Format("SELECT NursingFormData FROM NursingFormRecord(NOLOCK) WHERE Id='{0}'", Id);
            DataTable tab = SqlHelper.ExecuteDataset(sql, System.Data.CommandType.Text).Tables[0];
            var NursingFormData = Convert.ToString(tab.Rows[0]["NursingFormData"]);
            SBARHandOverDuty sbar = new SBARHandOverDuty();
            sbar = XmlUtil.XMLToObject<SBARHandOverDuty>(NursingFormData, Encoding.UTF8);
            if (!string.IsNullOrEmpty(sbar.RiQi))
                txtRiQi.DateTime = Convert.ToDateTime(sbar.RiQi);   //日期
            //病人类别
            var leibie = sbar.BingRenLieBie.Split('#');
            cheBingrenLeibie1.Checked = (leibie[0] == "1");
            cheBingrenLeibie2.Checked = (leibie[1] == "1");
            cheBingrenLeibie3.Checked = (leibie[2] == "1");
            cheBingrenLeibie4.Checked = (leibie[3] == "1");
            //护理级别
            var jibie = sbar.HuLiJiBie.Split('#');
            cheHuliJibie1.Checked = (jibie[0] == "1");
            cheHuliJibie2.Checked = (jibie[1] == "1");
            cheHuliJibie3.Checked = (jibie[2] == "1");
            memoRuYuanZhenDuan.Text = sbar.RuYuanZhenDuan;  //入院诊断
            memoXianZhuang.Text = sbar.JiaoBanBingQingXianZhuang;   //现状
            memoBeiJing.Text = sbar.JiaoBanBingQingBeiJing;  //背景
            memoPingGu.Text = sbar.JiaoBanBingQingPingGu;  //评估
            memoJianYi.Text = sbar.JiaoBanBingQingJianYi; //建议
            txtShiJian.Text = DateTimeHelper.HHmmssToHHmm(sbar.ShiJian);     //时间
            txtJiaoBanRen.Text = sbar.JiaoBanRen;//交班人签名
        }
        #endregion
    }
}